<template>
  <!-- 容器开始 -->
  <div class="app-container">
    <!-- 查询条件开始 -->
    <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
      <!-- 列开始  -->
      <el-form-item label="菜单名称" prop="menuName">
        <el-input
          v-model="queryParams.menuName"
          placeholder="请输入菜单名称"
          clearable
          size="small"
          style="width:240px"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="字典状态" clearable size="small" style="width:240px">
          <el-option v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button type="primary" icon="el-icon-refresh" size="mini" @click="restQuery">重置</el-button>
        <el-button type="danger" icon="el-icon-plus" size="mini" @click="handleAdd">添加</el-button>
        <el-button type="wanging" icon="el-icon-refresh" size="mini" @click="handelRefresh" />
      </el-form-item>
    </el-form>
    <!-- 查询条件结束 -->

    <!-- 数据表格开始 -->
    <el-table
      v-loading="loading"
      border
      :data="menuTableList"
      row-key="menuId"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column label="菜单名称" align="left" prop="menuName" />
      <el-table-column label="菜单类型" align="center" prop="menuType">
        <template slot-scope="scope">
          <el-tag
            :type="scope.row.menuType==='M'?'primary':scope.row.menuType==='C'?'danger':'success'"
          >
            {{ scope.row.menuType==='M'?'目录':scope.row.menuType==='C'?'菜单':'权限' }}
          </el-tag></template>
      </el-table-column>
      <el-table-column label="组件路径" align="center" prop="path" />
      <el-table-column label="权限标识" align="left" prop="preCode" />
      <el-table-column label="状态" align="center" prop="status" :formatter="statusFormatter" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button type="text" icon="el-icon-edit" size="mini" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button type="text" icon="el-icon-plus" size="mini" @click="handleAdd(scope.row)">添加</el-button>
          <el-button type="text" icon="el-icon-delete" size="mini" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
      <!-- 数据表格结束 -->

      <!-- 添加和修改的弹出层 -->
      <!-- 添加和修改的弹出层开始 -->
      <el-dialog
        :visible.sync="open"
        width="600px"
        center
        append-to-body
        :title="form.menuId!=null?'修改菜单':'添加菜单'"
      >
        <el-form ref="form" :model="form" :rules="rules" label-width="80px" @keyup.enter.native="handleSubmit()">
          <el-row>
            <el-col :span="24">
              <el-form-item label="上级菜单" prop="parentName">
                <treeselect
                  v-model="form.parentId"
                  :options="menuOptions"
                  :show-count="true"
                  :normalizer="normalizer"
                  placeholder="请选择上级菜单"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="菜单类型" prop="menuType">
                <el-radio-group v-model="form.menuType">
                  <el-radio label="M">目录</el-radio>
                  <el-radio label="C">菜单</el-radio>
                  <el-radio label="F">按钮</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="菜单名称" prop="menuName">
                <el-input v-model="form.menuName" placeholder="请输入菜单名称" clearable size="small" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="路由地址" prop="path">
                <el-input v-model="form.path" placeholder="请输入路由地址" clearable size="small" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item v-if="form.menuType==='F'" label="权限标识" prop="percode">
                <el-input v-model="form.percode" placeholder="请输入权限标识" clearable size="small" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态" prop="status">
                <el-radio-group v-model="form.status">
                  <el-radio
                    v-for="dict in statusOptions"
                    :key="dict.dictValue"
                    :label="dict.dictValue"
                    :value="dict.dictValue"
                  >{{ dict.dictLabel }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" placeholder="备注说明一下菜单的用处哦~" type="textarea" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="open = false">取 消</el-button>
        </span>
      </el-dialog>
    <!-- 添加和修改的弹出层结束 -->
      <!-- 添加和修改的弹出层 -->
    </el-table>
  </div>
  <!-- 容器结束 -->
</template>

<script>
// import the component
import Treeselect from '@riophae/vue-treeselect'
// import the styles
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { listAllMenus, selectMenuTree, getMenuById, addMenu, updateMenu, deleteMenuById } from '@/api/system/menu/menu'
import { handelTreeClone } from '@/utils/his-utils'
export default {
  // 刷新当前页
  inject: ['reload'],
  components: {
    Treeselect
  },
  data() {
    return {
      // 控制遮罩
      loading: false,
      // 菜单表的集合数据
      menuTableList: [],
      // 字典状态集合
      statusOptions: [],
      // 菜单树的数据
      menuOptions: [],
      // 是否打开弹出层
      open: false,
      // 查询参数
      queryParams: {
        menuName: undefined,
        status: undefined
      },
      // 记录选中的数据
      menuId: undefined,
      // 表单数据
      form: {},
      // 表单校验
      rules: { menuName: [{ required: true, message: '菜单名称不能为空', tirgger: 'blur' }] }
    }
  },
  created() {
    // 查询状态字典数据
    this.getDataByType('sys_normal_disable').then(res => {
      this.statusOptions = res.data
    })
    // 加载菜单数据
    this.getTableList()
  },
  methods: {
    // 翻译
    statusFormatter(row) {
      return this.selectDictLabel(this.statusOptions, row.status)
    },
    // 开始数据源
    getTableList() {
      this.loading = true
      listAllMenus(this.queryParams).then(res => {
        this.menuTableList = this.handelTreeClone(res.data, 'menuId')
        // console.log(this.handelTreeClone(res.data, 'menuId'))
        this.loading = false
      })
    },
    // 重置查询条件
    restQuery() {
      this.reset()
      this.getTableList()
    },
    // 条件查询
    handleQuery() {
      this.getTableList()
    },
    // 添加菜单
    handleAdd(row) {
      this.reset()
      this.getTreeSelect()
      // 判断行内添加和外部添加的区别
      if (row != null) { // 表示为行内
      // 把这个行内的菜单ID给到表单进行选中： 表示添加到这个菜单下去
        this.form.parentId = row.menuId
        // 判断如果类型是M那么只能添加C级菜单，如果是C那么只能添加F菜单
        if (row.menuType === 'M') {
          this.form.menuType = 'C'
        } else if (row.menuType === 'C') {
          this.form.menuType = 'F'
        }
      }
      this.open = true
    },
    // 修改菜单
    handleUpdate(row) {
      this.reset()
      this.getTreeSelect()
      // 根据ID查询菜单信息
      getMenuById(row.menuId).then(res => {
        this.form = res.data
        this.open = true
        // this.form.parentId = row.menuId
        // this.menuId = row
      })
    },
    // 提交表单
    handleSubmit() {
      // 判断当前选中的菜单是否为自己的子节点
      // getMenuById(this.form.parentId).then(res => {
      //   if (this.form.parentId === res.data.menuId) {
      //     this.msgError('不能设置子节点为父节点')
      //   } else {

      //   }
      // })
      // 开始
      this.$refs['form'].validate((valid) => {
        if (valid) {
          // 做添加
          this.loading = true
          if (this.form.menuId === undefined) {
            addMenu(this.form).then(res => {
              this.msgSuccess('保存成功')
              this.loading = false
              this.getTableList()// 列表重新查询
              this.open = false// 关闭弹出层
            }).catch(() => {
              this.loading = false
            })
          } else { // 做修改
            updateMenu(this.form).then(res => {
              this.msgSuccess('修改成功')
              this.loading = false
              this.getTableList()// 列表重新查询
              this.open = false// 关闭弹出层
            }).catch(() => {
              this.loading = false
            })
          }
        }
      })
    },
    // 重置表单
    reset() {
      this.form = {
        menuId: undefined,
        parentId: 0,
        menuName: undefined,
        percode: undefined,
        path: undefined,
        menuType: 'M',
        remark: undefined,
        status: '0'
      }
    },
    // 查询菜单下拉树
    getTreeSelect() {
      selectMenuTree().then(res => {
        this.menuOptions = []
        const menu = { menuId: 0, menuName: '主目录', children: [] }
        menu.children = handelTreeClone(res.data, 'menuId')
        this.menuOptions.push(menu)
      })
    },
    // 自定义下拉树的键名
    normalizer(node) {
      // 如果node当中有children但是长度小于0就把里面的children移除
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.menuId,
        label: node.menuName,
        children: node.children
      }
    },
    // 刷新当前页
    handelRefresh() {
      this.reload()
    },
    // 删除
    handleDelete(row) {
      const menuId = row.menuId
      this.$confirm('此操作将永久删除该菜单权限数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        deleteMenuById(menuId).then(res => {
          this.loading = false
          this.msgSuccess('删除成功')
          this.getTableList()// 全查询
        }).catch(() => {
          this.loading = false
        })
      }).catch(() => {
        this.msgError('删除已取消')
        this.loading = false
      })
    }
  }
}
</script>

<style>

</style>
